// 定义排序方向类型
type SortDirection = 'asc' | 'desc';

// 定义可排序的类型
type Sortable = number | string;

// 泛型排序函数
function sortArray<T extends Sortable>(
    array: T[],
    direction: SortDirection = 'asc'
): T[] {
    // 创建数组副本以避免修改原数组
    const result = [...array];

    return result.sort((a, b) => {
        // 确定比较结果
        let comparison = 0;
        if (a > b) {
            comparison = 1;
        } else if (a < b) {
            comparison = -1;
        }
        // 根据排序方向调整结果
        return direction === 'desc' ? -comparison : comparison;
    });
}

// 使用示例
const numbers = [3, 1, 4, 1, 5, 9, 2, 6];
const strings = ['banana', 'apple', 'cherry', 'date'];

// 数字排序
const sortedNumbersAsc = sortArray(numbers, 'asc');
const sortedNumbersDesc = sortArray(numbers, 'desc');

// 字符串排序
const sortedStringsAsc = sortArray(strings, 'asc');
const sortedStringsDesc = sortArray(strings, 'desc');

console.log('Numbers ascending:', sortedNumbersAsc);
console.log('Numbers descending:', sortedNumbersDesc);
console.log('Strings ascending:', sortedStringsAsc);
console.log('Strings descending:', sortedStringsDesc);

